//
//  ViewController.m
//  PostMessa
//
//  Created by never down on 15-5-12.
//  Copyright (c) 2015年 ygy_ios. All rights reserved.
//

#import "ViewController.h"
#import "AdddUserViewController.h"
#import "PostMessa-Prefix.pch"
#import "DBManager.h"
@interface ViewController ()

@end

@implementation ViewController
    CLLocation *checkinLocation;
    int i = 0;
    NSInputStream *inputStream ;
    NSOutputStream *outputStream;
    NSArray *tempAddArr;
    NSArray *resDataArray;

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    DBManager *dbm = [DBManager shareDBManagerInstance];
    //[dbm createItemDB];
    NSLog(@"%@",dbm.databasePath);
    [dbm insertUser];
     resDataArray = [dbm fetchUser];
    _messaText = self.messaText;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStylePlain target:self action:@selector(popToHome)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:self action:@selector(popToAddUser)];
    //常量
    const CGFloat wholeViewHeight = self.view.frame.size.height;
    const CGFloat wholeVieWidth = self.view.frame.size.width;

    //状态栏statusbar
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, wholeVieWidth, 20)];
    statusBarView.backgroundColor=[UIColor grayColor];
    
    //main视图
    self.contentView = [[UIView alloc] init];
    self.contentView.frame = CGRectMake(0, 20 + STATUSHEIGHT,wholeVieWidth,wholeViewHeight-20);
    self.contentView.backgroundColor = WHITE;

    self.messaText = [[UITextField alloc] initWithFrame:CGRectMake(14, self.contentView.frame.size.height-60, 200, 35)];
    _messaText.placeholder = @"please input your message in here ";
    _messaText.backgroundColor = [UIColor whiteColor];
    _messaText.borderStyle =  UITextBorderStyleBezel;
    
    CALayer * messaTextLayer = [_messaText layer];
    [messaTextLayer setMasksToBounds:YES];
    [messaTextLayer setCornerRadius:0];
    [messaTextLayer setBorderWidth:2.0];
    [messaTextLayer setBorderColor:[[UIColor blackColor] CGColor]];
    
    UITextField *messaText1 = [[UITextField alloc] initWithFrame:CGRectMake(15, self.contentView.frame.size.height-59, 200, 35)];
    CALayer * messaTextLayer1 = [messaText1 layer];
    [messaTextLayer1 setCornerRadius:0];
    [messaTextLayer1 setBorderWidth:2.0];
    [messaTextLayer1 setBorderColor:[[UIColor blackColor] CGColor]];

    [messaTextLayer setShadowColor:[UIColor blackColor].CGColor];
    [messaTextLayer setShadowOpacity:0.0f];
    [messaTextLayer setShadowOffset:CGSizeMake(10, 20)];
    
    UIButton *sendButton = [[UIButton alloc]init];
    sendButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [sendButton setTitle:@"Send" forState:UIControlStateNormal];
    [sendButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [sendButton.titleLabel setFont:[UIFont fontWithName:@"Times New Roman" size: 15]];
    [sendButton addTarget:self
                   action:@selector(sendMessage:)
         forControlEvents:UIControlEventTouchUpInside];
    
    CALayer * downButtonLayer = [sendButton layer];
    [downButtonLayer setMasksToBounds:YES];
    [downButtonLayer setCornerRadius:0];
    [downButtonLayer setBorderWidth:2.0];
    [downButtonLayer setBorderColor:[[UIColor blackColor] CGColor]];
    sendButton.frame = CGRectMake(wholeVieWidth-100, messaText1.frame.origin.y, 50, 36);
    
    UILabel *messagesView = [[UILabel alloc]init];
    messagesView.frame = CGRectMake(0,0,wholeVieWidth ,25);
    messagesView.backgroundColor = [UIColor blueColor];
    messagesView.text = @"Messages list";
    
    [self.contentView addSubview:messagesView];
    [self.contentView addSubview:_messaText];
    [self.contentView addSubview:sendButton];

    [self.contentView.layer setCornerRadius:0];
    [self.contentView.layer setBorderWidth:3.0];
    [self.contentView.layer setBorderColor:[[UIColor blackColor] CGColor]];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchesBegan)];
    [self.view addGestureRecognizer:tap];
    
    [self.view addSubview:statusBarView];
    [self.view addSubview:self.contentView];
    [self setMessagesTableView];
    [self setCoreLocations];
}

-(void)setMessagesTableView {
    //常量
    const CGFloat wholeViewHeight = self.view.frame.size.height;
    const CGFloat wholeVieWidth = self.view.frame.size.width;

    self.dataArray = [[NSMutableArray alloc]init];
    UITableView *messagesDetailTableView = [[UITableView alloc] init];
    messagesDetailTableView.delegate = self;
    messagesDetailTableView.dataSource = self;
    [self.contentView addSubview:messagesDetailTableView];
    messagesDetailTableView.frame = CGRectMake(0, self.contentView.frame.origin.y, wholeVieWidth, 300);
    self.messagesDetailTableView = messagesDetailTableView;
}

- (void)locationManager:(CLLocationManager *)manager
didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([self.locmanager respondsToSelector:@selector(requestAlwaysAuthorization)]) {                [self.locmanager requestWhenInUseAuthorization];
            }
            break;
        default:
            break;
    }
}

-(void)setCoreLocations{
    self.locmanager = [[CLLocationManager alloc]init];
    self.locmanager.delegate = self;
    [self.locmanager requestAlwaysAuthorization];
    self.locmanager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locmanager.distanceFilter = kCLDistanceFilterNone;
//    dispatch_sync(nil, ^(){
//        NSString *str = @"";
//        str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        
//        NSMutableURLRequest *rq = [[NSMutableURLRequest alloc]init];
//        [rq setURL:[NSURL URLWithString:str]];
//        
//        [rq setCachePolicy:NSURLRequestReloadIgnoringCacheData];
//        [rq setTimeoutInterval:60];
//        [rq setHTTPShouldHandleCookies:FALSE];
//        [rq setHTTPMethod:@"GET"];
//        
//        
//        NSHTTPURLResponse * res;
//        NSData *resData = [NSURLConnection sendSynchronousRequest:rq returningResponse:&res error:nil];
//        NSString *strRes = [[NSString alloc]initWithData:resData encoding:NSUTF8StringEncoding];
//        [res statusCode];
//        
//        
//        
//    });
//    dispatch_queue_t queue = dispatch_queue_create("queue", nil);
//    
//    dispatch_async(queue, ^{
//        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:
//                                        [NSURL URLWithString: @"http://10.206.17.162:8888"]];
//        
//        [request setHTTPMethod: @"POST"];
//        
//        NSString* str = @"aaa=bbb&";
//        
//        [request setHTTPBody: [str dataUsingEncoding: NSUTF8StringEncoding]];
//        
//        NSURLResponse* response = [[NSURLResponse alloc] init];
//        
//        NSError* error;
//        
//        [NSURLConnection sendSynchronousRequest: request returningResponse: &response
//                                          error: &error];
//        
//        // TODO
//        
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [MBProgressHUD dismiss];
//            
//            [self.ta]
//        });
//    });

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)touchesBegan{
    [self.view endEditing:YES];
}

- (void)sendMessage:(id)info{
    [self.locmanager startUpdatingLocation];

    NSString *str = self.messaText.text;
//    NSArray *arr = [[NSArray alloc]initWithObjects:str,nil];
//    [self.dataArray addObject: str];
    [self.dataArray insertObject:str atIndex:i];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
    NSArray *insertIndexPath = [NSArray arrayWithObjects:indexPath, nil];

    [self.messagesDetailTableView insertRowsAtIndexPaths:insertIndexPath withRowAnimation:UITableViewRowAnimationRight];
    [self.messagesDetailTableView reloadData];
    NSLog(@"%lu %d",(unsigned long)[self.dataArray count],i);
    i++;
    
}

#pragma mark － UITableViewDataSource

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([self.dataArray count] == 0)
    {
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        return 0;
    }else{
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        return [resDataArray count];
    }
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIndentifier = @"OrderDetailCell";
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIndentifier];
    [self setExtraCellLineHidden:tableView];
//  [[cell textLabel] setText:self.dataArray[indexPath.row]] ;

    NSString *a = [NSString stringWithFormat:@"%0.0f", checkinLocation.coordinate.latitude];
    NSString *b = [NSString stringWithFormat:@"%0.0f", checkinLocation.coordinate.longitude];
    NSString *str =self.dataArray[indexPath.row];
    NSMutableString *obj = [[NSMutableString alloc] initWithCapacity:50];
    User *u = (User *)resDataArray[indexPath.row];
    [obj appendString:u.name];
    //[obj appendString:str];
    [obj appendString:@"       from"];
    [obj appendString:a];
    [obj appendString:@","];
    [obj appendString:b];
    [[cell textLabel] setText: obj] ;
    return cell;
}

-(void)setExtraCellLineHidden:(UITableView *)tableView{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}



#pragma mark － cllocation

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation{
    NSLog(@"%f;%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
    checkinLocation = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude
                                                 longitude:newLocation.coordinate.longitude ];
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error{
    NSLog(@"have an error in this");
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *indexPaths = [NSMutableArray array];
//    NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
//    [indexPaths addObject:indexPath1];
    [self.dataArray removeObjectAtIndex:indexPath.row];
    --i;
    NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
    [indexPaths addObject:indexPath2];
//    [self.dataArray removeObject:[self.dataArray objectAtIndex:indexPath.row]];
//    NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:indexPath.row inSection:0];
    
    [self.messagesDetailTableView deleteRowsAtIndexPaths:indexPaths  withRowAnimation: UITableViewRowAnimationLeft];
    
}

-(void)popToHome{
    
}

-(void)popToAddUser{
    AdddUserViewController *addUserVC = [[AdddUserViewController alloc]init];
    //    addUserVC.delegate = self;
    [self presentViewController:addUserVC animated:YES completion:nil];
    addUserVC.block = ^(NSArray *arr){
        tempAddArr = arr;
        NSLog(@"%@",tempAddArr);
        
    };
}


#pragma mark - socket
- (void)connect{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"10.206.17.162", 8888, &readStream, &writeStream);
NSInputStream *inputStream = (NSInputStream *)CFBridgingRelease(readStream);
NSOutputStream *outputStream = (NSOutputStream *)CFBridgingRelease(writeStream);
[inputStream setDelegate:self];
[outputStream setDelegate:self];

[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
//    NSLog(inputStream.)
}

//调用此接口与socket断开连接
- (void)disConnect{
    if (inputStream){
        [inputStream close];
        inputStream = nil;
    }
    
    if (outputStream){
        [outputStream close];
        outputStream = nil;
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse{
    
}

@end








